import tkinter as tk
# 数学库
from math import sqrt

# 定义商品和用户数据
GOODS = [
    ['苹果', '梨', '西瓜', '葡萄'],
    ['苹果', '西瓜', '葡萄', '梨'],
    ['西瓜', '梨', '苹果'],
    ['芒果', '香蕉', '龙眼', '荔枝'],
    ['香蕉', '龙眼', '木瓜', '芒果']
]
USERS = ['甲', '乙', '丙', '丁', '戊']

# 计算用户相似性
def user_similarity():
    box.delete(0, tk.END)
    for i in range(len(GOODS) - 1):
        as1 = GOODS[i]
        as2 = GOODS[i + 1]
        # 集合A与集合B的交集/集合A的数量与集合B的数量的积的平方根
        ass = [num for num in as1 if num in as2]
        num = len(ass) / sqrt(len(as1) * len(as2)) * 100
        # 保留两位小数并显示到列表中
        ratio = round(num, 2)
        user = f'用户{USERS[i]}与用户{USERS[i + 1]}的相似率约≈{ratio}%'
        box.insert(tk.END, user)

# 将GOODS转换成商品购买者清单
def to_goods():
    JS = {}
    for k, user in enumerate(USERS):
        for good in GOODS[k]:
            if good in JS:
                JS[good].append(user)
            else:
                JS[good] = [user]
    return JS

# 计算商品相似性
def goods_similarity():
    box.delete(0, tk.END)
    JS = to_goods()
    arr = list(JS.keys())
    # 遍历商品
    for i in range(len(arr) - 1):
        as1 = JS[arr[i]]
        as2 = JS[arr[i + 1]]
        # 集合A与集合B的交集/集合A的数量与集合B的数量的积的平方根
        ass = [num for num in as1 if num in as2]
        num = len(ass) / sqrt(len(as1) * len(as2)) * 100
        ratio = round(num, 2)
        goods = f'{arr[i]} 与 {arr[i + 1]} 的相似率约≈{ratio}%'
        box.insert(tk.END, goods)

# 创建Tkinter窗口
root = tk.Tk()
root.title('相似的用户与相似的物品')
root.geometry("1024x768")

# 创建按钮
calculate_user_button = tk.Button(root, text='计算用户相似性', command=user_similarity)
calculate_user_button.pack()

calculate_goods_button = tk.Button(root, text='计算商品相似性', command=goods_similarity)
calculate_goods_button.pack()

# 创建列表框
box = tk.Listbox(root)
box.pack(fill="x")

# 运行Tkinter主循环
root.mainloop()